package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.djsearch.R;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.bean.PlaneTicket;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.djsearch.widget.WheelMain;
import com.djsearch.widget.WheelView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * 首页机票进入页面（该页面查询机票）
 * @author chenyang2
 *
 */
public class SearchJiPiaoActivity extends BaseActivity{
   
	private Context mContext;
	private LayoutInflater inflater;
	private Button backBtn,searchBtn;
	private TextView searchJiPiao,teJiaJiPiao;//顶部点击 ：机票查询/特价机票
	private HorizontalScrollView searchResultScrollView;//机票查询结果显示
	private RelativeLayout beginCityLayout,arriveCityLayout,chufaTimeLayout;
	private TextView beginCityText,arriveCityText;//出发城市 到达城市
	private List<PlaneTicket> ticketList;
	private PopupWindow popuWindow;
	private TextView chufaTimeCityText;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_jipiao_layout);
		mContext = this;
		inflater = (LayoutInflater) this
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ticketList = new ArrayList<PlaneTicket>();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
		
		
	}
	
	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		backBtn = (Button)findViewById(R.id.btnBack);
		searchBtn = (Button)findViewById(R.id.searchBtn);
		searchJiPiao = (TextView)findViewById(R.id.searchJiPiaoText);
		teJiaJiPiao = (TextView)findViewById(R.id.searchTeJiaText);
		beginCityLayout = (RelativeLayout)findViewById(R.id.beginCityLayout);
		beginCityText = (TextView)findViewById(R.id.beginCityText);
		arriveCityLayout = (RelativeLayout)findViewById(R.id.arriveCityLayout);
		chufaTimeLayout = (RelativeLayout)findViewById(R.id.chufaTimeLayout);
		chufaTimeCityText = (TextView)findViewById(R.id.chufaTimeCityText);
		arriveCityText = (TextView)findViewById(R.id.arriveCityText);
		searchResultScrollView = (HorizontalScrollView)findViewById(R.id.jiPiaoSearchResltView);
		getJiPiaoResultData();
	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, MainActivity.class, 2);
			}
		});
		/**
		 * 点击查询开始查询机票
		 */
		searchBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (beginCityText.getText().toString().equals("")) {
					startAnimation(beginCityLayout);
				} else if (arriveCityText.getText().toString().equals("")) {
					startAnimation(arriveCityLayout);
				} else if (beginCityText.getText().toString().equals(arriveCityText.getText().toString())) {
					startAnimation(beginCityLayout);
					startAnimation(arriveCityLayout);
				} else if (chufaTimeCityText.getText().toString().equals("")) {
					startAnimation(chufaTimeLayout);
				} else {
					setRequestParamsStructData();
					requestData(initRequestMap());
				}
				
			}
		});
		
		searchJiPiao.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(mContext, "测试代码", 5000).show();
				v.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
				teJiaJiPiao.setBackgroundResource(R.drawable.fenlantiao_top);
			}
		});
		teJiaJiPiao.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(mContext, "测试代码", 5000).show();
				v.setBackgroundResource(R.drawable.fentiaolan_top_seleted);
				searchJiPiao.setBackgroundResource(R.drawable.fenlantiao_top);
			}
		});
		
		beginCityLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();   
				intent.setClass(mContext, ChooseCityActivity.class);   
				startActivityForResult(intent, 1);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
		arriveCityLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();   
				intent.setClass(mContext, ChooseCityActivity.class);   
				startActivityForResult(intent, 2);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
		
		chufaTimeLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDateTimePicker(v);
			}
		});
	}

	
	private void setRequestParamsStructData() {
		RequestParamsStruct.startCity = beginCityText.getText().toString();
		RequestParamsStruct.endCity = arriveCityText.getText().toString();
		RequestParamsStruct.date = chufaTimeCityText.getText().toString();
	}

	private Map<String, String> initRequestMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("queryByType", RequestParamsStruct.queryByType);
		map.put("startCity", RequestParamsStruct.startCity);
		map.put("endCity", RequestParamsStruct.endCity);
		map.put("date", RequestParamsStruct.date);
		map.put("queryByOrder", RequestParamsStruct.queryByOrder);
		map.put("page", RequestParamsStruct.page);
		map.put("pageNum", RequestParamsStruct.pageNum);
		return map;
	}
	
	
	/**
	 * 开始查询，请求数据
	 */
	private void requestData(Map<String, String> map) {

		IRequest request = new JSONReq("plane",map);
//		request.putParam("queryByType", "1");
////		request.putParam("startCity", "\u90d1\u5dde");
//		request.putParam("startCity", "上海");
////		request.putParam("endCity", "\u4e0a\u6d77");
//		request.putParam("endCity", "深圳");
//		request.putParam("date", "2013-05-21");
//		request.putParam("queryByOrder", "1");
//		request.putParam("page", "1");
//		request.putParam("pageNum", "20");
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在查询...");
				
			}
			/**
			 * {"startTime":"2013-05-21T08:00:00","flight":"FM9328","startCity":"新郑国际机场",
			 * "price":"230","planeType":"738",
			 * "name":"上海航空有限公司","endCity":"浦东国际机场","endTime":"2013-05-21T09:40:00","sale":"0.29"}
			 * 
			 * 
			 * {"priceType":"普通","endCity":"首都国际机场","airlineDibitCode":"中国国际航空股份有限公司",
			 * "endTime":"2013-04-19T10:15:00","sale":"1","startTime":"2013-04-19T07:55:00",
			 * "arriveAirportCode":"北京(首都国际机场)",
			 * "flight":"CA1858","startCity":"虹桥国际机场",
			 * "departAirportCode":"上海(虹桥国际机场)",
			 * "price":"1130","planeType":"333","name":"中国国际航空股份有限公司","quantity":"10"}
			 * 
			 */
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
					getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					Toast.makeText(mContext, "失败", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
				missDialog();
			}
			
		});
	}

	private static class RequestParamsStruct{
		static String queryByType = "1";
		static String startCity;
		static String endCity;
		static String date;
		static String queryByOrder = "1";
		static String page = "1";
		static String pageNum = "30";
	}
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		ticketList.clear();
		super.onResume();
	}

	private void getJiPiaoResultData() {
		LinearLayout linearLayout = (LinearLayout)findViewById(R.id.jiPiaoResultLayout);
		for (int i = 0;i<10;i++) {
			LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.jipiao_result_layout_items, null);
			linearLayout.addView(layout);
		}
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		try {
			Gson gson = new Gson();   
	        Type type = new TypeToken<List<PlaneTicket>>(){}.getType();  //指定集合对象属性  
	        List<PlaneTicket> fromJson = gson.fromJson(response.getString("returnMessage"), type);
	        ticketList.addAll(fromJson);
		} catch (JsonSyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		if (ticketList.size() != 0) {
			Intent intent=new Intent(mContext,JiPiaoActivity.class);
			intent.putExtra("data", ticketList.toArray());
			Bundle localBundle = new Bundle();
			intent.putExtras(localBundle);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		} else {
			Toast.makeText(mContext, "暂无数据", 5000).show();
		}
		
	}
	

	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		startActivity(mContext, MainActivity.class, 2);
		return super.onKeyDown(keyCode, event);
	}
	
	
	@Override   
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {   
	       // TODO Auto-generated method stub    
	       Bundle bundle;   
	       switch (requestCode) {   
	       case 1:   
	           if (resultCode == RESULT_OK){   
	               bundle = data.getExtras();   
	               String beginName = bundle.getString("NAME"); 
	               beginCityText.setText(beginName);
	           }  
	           break;
	       case 2:  
	    	   if (resultCode == RESULT_OK){   
	    		   bundle = data.getExtras();   
	               String nameString = bundle.getString("NAME");  
	               arriveCityText.setText(nameString);
	           } 
	           break;   
	       default:   
	           break;   
	       }   
	    }  
	
    private void showDateTimePicker(View v) {

		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.time_layout, null);
		View viewTwo = inflater.inflate(R.layout.time_popu_layout, null);
		popuWindow = new PopupWindow(  
				viewTwo, getWidth(), 2*getHeight()/5-50);
		final WheelMain main = new WheelMain(popuWindow, view);
		main.showDateTimePicker(v);
		Button btn_sure = (Button) view.findViewById(R.id.btn_datetime_sure);
		btn_sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popuWindow.dismiss();
				String time = main.getTime();
				String str[] = time.split("-");
				if (str[1].length() == 1) {
					str[1] = "0" + str[1];
				}
				if (str[2].length() == 1) {
					str[2] = "0" + str[2];
				}
				String newTime = str[0] + "-" + str[1] + "-" + str[2];
				chufaTimeCityText.setText(newTime.toString());
//				System.out.println(main.getTime());
			}
		});
	}
	

}
